package com.tbit.uqbike.webmanager.controller;

import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.constant.WorkType;
import com.tbit.uqbike.object.pojo.WorkOrderVO;
import com.tbit.uqbike.object.pojo.dto.mainManage.BarChartWorkOrderDTO;
import com.tbit.common.entity.pojo.vo.DateResult;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.uqbike.service.business.WorkOrderService;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.StringUtil;
import com.tbit.uqbike.webmanager.util.excel.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author ：hzw
 * @date ：Created in 2021/8/16 15:14
 * @description：工单统计
 * @modified By：
 * @version: $
 * workType=1:换电工单
 * workType=2：调度工单
 * workType=3：挪车工单
 */
@Slf4j
@RestController
@RequestMapping(value = "/workOrder", produces = BaseController.MEDIA_JSON_UTF8)
public class WorkOrderController extends BaseController {
    @Autowired
    private WorkOrderService workOrderService;

    /**
     * 柱状图数据
     * workType:工单种类
     * buildType:工单类型
     * state:工单状态
     * isValid:工单是否有效：0无效，1有效
     * locationType:挪车类型 0：超出区域，1：站外
     */
    @RequestMapping("/statisticsByTime")
    public JsonResult statisticsByTime(BarChartWorkOrderDTO barChartWorkOrderDTO) {
        Assert.notNulls("参数有误", barChartWorkOrderDTO.getAccountId(), barChartWorkOrderDTO.getStartTime(), barChartWorkOrderDTO.getEndTime());
        barChartWorkOrderDTO.setValidList(StringUtil.getIntegerList(barChartWorkOrderDTO.getIsValid()));
        List<List<DateResult>> powerWorkOrder = workOrderService.statisticsByTime(barChartWorkOrderDTO);
        return JsonResult.ok(powerWorkOrder);

    }

    /**
     * 数据详情展示页面
     */
    @RequestMapping("/queryPage")
    public JsonResult queryPage(Integer accountId, String userCode, Integer accountUserId, Long startTime,
                                Long endTime, String regionIds, Integer workType, Integer buildType, String isValid, Integer locationType) {

        Assert.notNull(accountId, "ver.accountId.notNull");
        Assert.notNull(startTime, "ver.startTime.notNull");
        Assert.notNull(endTime, "ver.endTime.notNull");
        List<Integer> validList = StringUtil.getIntegerList(isValid);
        List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
        List<WorkOrderVO> list = workOrderService.queryPage(accountId, userCode, accountUserId, startTime, endTime, regionIdList, workType, buildType, validList, locationType);
        return JsonResult.ok(startPage(list), list.size());
    }

    /**
     * 数据详情导出
     */
    @RequestMapping("/exportByTime")
    public void exportByTime(Integer accountId, Integer accountUserId, Long startTime, Long endTime, String userCode,
                             Integer workType, Integer buildType, String isValid, String regionIds,Integer locationType,
                             HttpServletResponse response) {
        Assert.notNull(accountId, "ver.accountId.notNull");
        Assert.notNull(startTime, "ver.startTime.notNull");
        Assert.notNull(endTime, "ver.endTime.notNull");

        List<Integer> validList = StringUtil.getIntegerList(isValid);
        List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
        List<WorkOrderVO> list = workOrderService.exportByTime(accountId, userCode, accountUserId, startTime, endTime, regionIdList, workType, buildType, validList, locationType);

        LinkedHashMap<String, String> titleMap = new LinkedHashMap();
        titleMap.put("workOrderId", "工单编号");
        String excelName = "工单详细导出";
        http:
//adminv3test.uqbike.cn/workOrder/exportByTime.do?startTime=1680278400000&endTime=1680623999000&accountUserId=&accountId=10293&token=7973bc17-1dc4-40e3-80ac-a562ebe3d0f3&workType=&buildType=2
        if (WorkType.workType_HD.equals(workType) && buildType.equals(WorkType.buildType_ZD)) {
            excelName = "换电工单统计";
            titleMap.put("userCode", "车辆编号");
            titleMap.put("accountUserName", "运维人名称");
            titleMap.put("phone", "手机号");
            titleMap.put("changeTime", "换电时间");
            titleMap.put("oldSoc", "换电前电量");
            titleMap.put("newSoc", "换电后电量");
            titleMap.put("isValid", "审核状态");
            titleMap.put("auditName", "审核人");
            titleMap.put("auditTime", "审核时间");
            titleMap.put("remark", "备注");
        } else if (WorkType.workType_NC.equals(workType) && buildType.equals(WorkType.buildType_ZD)) {
            excelName = "挪车工单统计";
            titleMap.put("userCode", "车辆编号");
            titleMap.put("getUserName", "运维人名称");
            titleMap.put("phone", "手机号");
            titleMap.put("moveStartTime", "挪车时间");
            titleMap.put("moveEndTime", "完成时间");
            titleMap.put("oldParkPoint", "开始位置");
            titleMap.put("newParkPoint", "结束位置");
            titleMap.put("isValidList", "审核状态");
            titleMap.put("locationTypeName", "挪车类型");
            titleMap.put("moveRemark", "备注");
        } else if (WorkType.workType_WX.equals(workType) && buildType.equals(WorkType.buildType_ZD)) {
            excelName = "维修工单统计";
            titleMap.put("userCode", "车辆编号");
            titleMap.put("accountUserName", "运维人名称");
            titleMap.put("buildTime", "添加时间");
            titleMap.put("getTime", "接单时间");
            titleMap.put("repairTypes", "维修类型");
            titleMap.put("repairRemark", "备注");
            titleMap.put("repairStates", "维修状态");
        } else if (buildType.equals(WorkType.buildType_SD)) {
            excelName = "手动工单统计";
            titleMap.put("getUserName", "处理人");
            titleMap.put("buildTime", "工单生成时间");
            titleMap.put("finishTime", "工单完成时间");
            titleMap.put("title", "标题");
            titleMap.put("content", "描述");
            titleMap.put("priority", "优先级");
            titleMap.put("workName", "类型");
            titleMap.put("newParkPoint", "位置");
        } else if(WorkType.workType_DU.equals(workType) && buildType.equals(WorkType.buildType_ZD)){
            excelName = "调度工单统计";
            titleMap.put("userCode", "车辆编号");
            titleMap.put("getUserName", "运维人名称");
            titleMap.put("phone", "手机号");
            titleMap.put("moveStartTime", "挪车时间");
            titleMap.put("moveEndTime", "完成时间");
            titleMap.put("oldParkPoint", "开始位置");
            titleMap.put("newParkPoint", "结束位置");
            titleMap.put("isValidList", "审核状态");
            titleMap.put("moveRemark", "备注");
        }
        if (list.isEmpty()) {
            //为了让他导出表头 空列表
            WorkOrderVO workOrderVO = new WorkOrderVO();
            list.add(workOrderVO);
        }
        try {
            ExcelUtils.listToExcel(list, titleMap, excelName, response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 数据展示总览
     */
    @RequestMapping("/getByType")
    public JsonResult getByType(@NotNull(message = "ver.accountId.notNull") Integer accountId, Integer accountUserId,
                                @NotNull(message = "ver.startTime.notNull") Long startTime, String regionIds, Integer type,
                                @NotNull(message = "ver.endTime.notNull") Long endTime, Integer workType,
                                @RequestParam(defaultValue = "10") Integer rowCount, Integer buildType,Integer locationType,
                                @RequestParam(defaultValue = "1") Integer pageNO, String sort, HttpServletResponse response) {
        List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
        List<WorkOrderVO> list = workOrderService.getByType(accountId, accountUserId, startTime, endTime, rowCount, pageNO, regionIdList, type, workType, buildType, locationType);
        /**升序排列*/
        List<WorkOrderVO> ascendingList = list.stream().sorted(Comparator.comparing(WorkOrderVO::getTotal)).collect(Collectors.toList());
        /**降序排列*/
        List<WorkOrderVO> descendingList = list.stream().sorted(Comparator.comparing(WorkOrderVO::getTotal).reversed()).collect(Collectors.toList());
        PageInfo pageInfo = new PageInfo();
        if ("asc".equals(sort)) {
            pageInfo = new PageInfo(ascendingList);
        } else if ("desc".equals(sort)) {
            pageInfo = new PageInfo(descendingList);
        }

        return JsonResult.ok(pageInfo.getList(), (int) pageInfo.getTotal());

    }

    /**
     * 数据总览导出
     */
    @RequestMapping("/exportByTimeAndPersonnel")
    public void exportByTimeAndPersonnel(@NotNull(message = "ver.accountId.notNull") Integer accountId, Integer accountUserId,
                                         @NotNull(message = "ver.startTime.notNull") Long startTime,
                                         @RequestParam(required = false, value = "regionIds") String regionIds,
                                         @RequestParam(required = false, value = "type") Integer type, Integer buildType,
                                         @NotNull(message = "ver.endTime.notNull") Long endTime, Integer workType,Integer locationType,
                                         @RequestParam(defaultValue = "10") Integer rowCount, @RequestParam(defaultValue = "1") Integer pageNO,
                                         HttpServletResponse response) {
        List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
        List<WorkOrderVO> list = workOrderService.getByType(accountId, accountUserId, startTime, endTime, rowCount, pageNO, regionIdList, type, workType, buildType, locationType);
        String excelName = "工单总览导出-默认";
        if (WorkType.workType_HD.equals(workType) && WorkType.buildType_ZD.equals(buildType)) {
            excelName = "换电工单总览";
        } else if (WorkType.workType_NC.equals(workType) && WorkType.buildType_ZD.equals(buildType)) {
            excelName = "挪车工单总览";
        } else if (WorkType.workType_WX.equals(workType) && WorkType.buildType_ZD.equals(buildType)) {
            excelName = "维修工单总览";
        } else if (WorkType.buildType_SD.equals(buildType)) {
            excelName = "手动工单总览";
        }
        LinkedHashMap<String, String> titleMap = new LinkedHashMap<>();
        if (type == 0) {
            titleMap.put("getUserPhone", "手机号码");
            titleMap.put("getUserName", "姓名");
            titleMap.put("total", "总次数");
        } else if (type == 1) {
            titleMap.put("regionName", "分区");
            titleMap.put("total", "总次数");
        }
        if (list.isEmpty()) {
            //为了让他导出表头
            List<WorkOrderVO> defaultList = new ArrayList<>();
            WorkOrderVO workOrderVO = new WorkOrderVO();
            workOrderVO.setGetUserPhone("");
            workOrderVO.setGetUserName("");
            workOrderVO.setTotal(null);
            workOrderVO.setRegionName("");
            defaultList.add(workOrderVO);
            list = defaultList;
        }
        try {
            ExcelUtils.listToExcel(list, titleMap, excelName, response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 审核操作
     */
    @RequestMapping("/auditOperation")
    public JsonResult auditOperation(WorkOrderVO workOrderVO, HttpServletRequest request) {
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
        workOrderService.updateAudit(workOrderVO, loginInfo);
        return JsonResult.ok();
    }

}
